package com.api.ld.web;

import com.weaver.general.BaseBean;
import com.engine.ld.functions.sap.kccx.ZMM_INVENTORYINFO_QUERY_BindingStub;
import com.engine.ld.optimize.Kccx;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ZhangLei
 * @date 2021/7/1
 * 库存信息查询
 */
public class KccxAction {
    public static final BaseBean bb = new  BaseBean();

    public Map<String,Object> KccxHandle(String matnr, String werks){
        Map<String,Object> sapBackMap = new HashMap<>();
        Kccx kccx = new Kccx();
        try {
            ZMM_INVENTORYINFO_QUERY_BindingStub bindingStub = new ZMM_INVENTORYINFO_QUERY_BindingStub();
            String SAPBackXml = bindingStub.ZMM_INVENTORYINFO_QUERY(kccx.doKccx(matnr, werks));
            String realXml = trimXmlStr(SAPBackXml);
            SAXReader reader = new SAXReader();
            Document document = null;
            document = reader.read(new ByteArrayInputStream(realXml.getBytes(StandardCharsets.UTF_8)));
            Element root = document.getRootElement();
            List<Element> elements = root.elements();
            for (Element element : elements) {
                sapBackMap.put(element.getName().toLowerCase(),element.getData());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sapBackMap;
    }

    /**
     * 去除<_--5CTYPE_--3DSTRING>之前部分，去除</_--5CTYPE_--3DSTRING>之后部分
     * @param xmlString xml字符串
     * @return 去除头尾部分的xml字符串
     */
    private static String trimXmlStr(String xmlString) {
        if(!xmlString.contains("<_--5CTYPE_--3DSTRING>")) {
            return xmlString;
        }
        int start = xmlString.indexOf("<_--5CTYPE_--3DSTRING>") + "<_--5CTYPE_--3DSTRING>".length();
        int end = xmlString.indexOf("</_--5CTYPE_--3DSTRING>");
        return xmlString.substring(start, end).trim();
    }
}
